/*
 * UIText.cpp
 */

#include "UIText.h"
#include <iostream>
#include <SDL/SDL_ttf.h>

UIText::UIText(UIText::TextType type, float x, float y, float height, float angle,
      std::string text, RGBAColor color) :
  _mode(type), _angle(angle), _text(text), _color(color) {
  _xpos = x;
  _ypos = y;
  _depth = 0.;
  _height = height;
  _width = 0;
  initSDLTTFSupport();
  if (!set(text)) {
    std::cout << "Cannot render text as an OpenGL Texture : " << text
        << std::endl;
  }
}

UIText::~UIText() {
  quitSDLTTFSupport();
  glDeleteTextures(1, &_tex);
}

void UIText::draw() {
  //glEnable(GL_BLEND);
  //glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

  glPushMatrix();

  glTranslatef(_xpos, _ypos, _depth);

  glEnable(GL_TEXTURE_2D);
  glBindTexture(GL_TEXTURE_2D, _tex);

  glBegin(GL_QUADS);

  glNormal3f(0.0, 0.0, 1.0);

  glTexCoord2d(-1, 0);
  glVertex3f(0.0, 0.0, 0.0);
  glTexCoord2d(-1, -1);
  glVertex3f(0.0, _height, 0.0);
  glTexCoord2d(0, -1);
  glVertex3f(_width, _height, 0.0);
  glTexCoord2d(0, 0);
  glVertex3f(_width, 0.0, 0.0);

  glEnd();

  glPopMatrix();

  glDisable(GL_BLEND);
}

bool UIText::set(std::string& text) {
  TTF_Font* fntFreeSerif = TTF_OpenFont("fonts/FreeSerif.ttf", 72);
  SDL_Color fntColor = { _color.red(), _color.green(), _color.blue(), 0 };

  if (fntFreeSerif) {
    SDL_Surface* surface = TTF_RenderText_Blended(fntFreeSerif, _text.c_str(), fntColor);
    int w, h;
    TTF_SizeText(fntFreeSerif, _text.c_str(), &w, &h);
    _width = (_height * (float)w) / (float)h;

    if (!surface) {
      std::cout << "TTF_RenderText_Blended: " << TTF_GetError() << std::endl;
      TTF_CloseFont(fntFreeSerif);
      return false;
    } else {
      glGenTextures(1, &_tex);
      glBindTexture(GL_TEXTURE_2D, _tex);
      glColor3f(1.0,1.0,1.0);
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

      SDL_LockSurface(surface);
      glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, surface->w, surface->h, 0,
          GL_RGBA, GL_UNSIGNED_BYTE, surface->pixels);
      SDL_UnlockSurface(surface);
      SDL_FreeSurface(surface);
      TTF_CloseFont(fntFreeSerif);
      return true;
    }
  } else {
    std::cout << "TTF_OpenFont: " << TTF_GetError() << std::endl;
    return false;
  }
}

void UIText::initSDLTTFSupport() {
  if (TTF_Init() == -1) {
    std::cout << "TTF_Init: " << TTF_GetError() << std::endl;
  }
}

void UIText::quitSDLTTFSupport() {
  TTF_Quit();
}
